#pragma once

#include<iostream>
#include<assert.h>

namespace xiaolin
{
	class string
	{
	public:

		typedef char* iterator;
		typedef const char* const_iterator;

		iterator begin()
		{
			return _str;
		}
		const_iterator begin()const
		{
			return _str;
		}

		iterator end()
		{
			return (_str + _size);
		}
		const_iterator end()const
		{
			return (_str + _size);
		}

		/*string(const char* str="")
			: _str(new char[_capacity + 1])
			, _size(strlen(str))
			, _capacity(_size)
		{
			strcpy(_str, str);
		}*/
		string(const char* str = "")
			: _size(strlen(str))
			, _capacity(_size)
			, _str(new char[_capacity + 1])

		{
			strcpy(_str, str);
		}
		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}

		const char* c_str()const
		{
			return _str;
		}

		size_t size() const
		{
			return _size;
		}

		char& operator[] (size_t pos)
		{
			assert(pos < _size);
			return _str[pos];
		}
		const char& operator[] (size_t pos)const
		{
			assert(pos < _size);
			return _str[pos];
		}
		void reserve(size_t n = 0)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n+1];
				strcpy(tmp, _str);
				delete[]_str;
				_str = tmp;
				_capacity = n;
			}
		}

		string& append(const char* str)
		{
			size_t len = strlen(str);
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}
			strcpy(_str + _size, str);
			_size += len;
			return *this;
		}

		void push_back(char c)
		{
			if (_size == _capacity)
			{
				reserve(_capacity ==0?4:_capacity*2);
			}
			_str[_size] = c;
			_size++;
			_str[_size] = '\0';
		}

		string& operator+= (const char* str)
		{
			 append(str);
			 return *this;
		}
		string& operator+= (char c)
		{
			push_back(c);
			return *this;
		}

	private:
		
		size_t _size;
		size_t _capacity;
		char* _str;
		
	};
}
